<template>
<div class="noticeofdelivery">


  <div class="head">
    <h2>发货通知单</h2>
    <div class="btns clearfix">
      <el-button class="bind" v-show="!hasBind" :disabled="!editable" type="primary" @click="bindOrder">绑定订单</el-button>
      <!-- <el-button class="export"  :disabled="hasBind ? (!editable) : true" type="primary" @click="exportMethod">导出</el-button> -->
    </div>

    <div class="select-orders">
      <el-row :gutter="20">
        <el-col :span="10">
          <div>
            <p class="select-orders-line">
              选中的外贸订单
              <el-button v-show="hasBind ? editable : false"  @click="bindOrder" type="text">点击修改</el-button>
            </p>
            <ul>
              <!-- <li v-if="showftc"><a :href="'#/initiatingprocess/businessform?dTab=3&formInstId='+ showftc.id + '&formServiceName=' +  showftc.formServiceName">{{this.data.documentprocess_fdn_bindFContracts[0]}}</a></li> -->
              <li><a href="#">{{data.documentprocess_fdn_bindFContracts[0]}}</a></li>
            </ul>
          </div>
        </el-col>
        <el-col :span="10" :offset="4" >
          <div>
            <p class="select-orders-line">选中的内贸订单</p>
            <ul>

              <!-- <li v-for="item in this.data.documentprocess_fdn_bindDContracts ">
                <a href="#">{{item}}</a>
              </li>
               -->
              <li>
                <a href="#">{{data.documentprocess_fdn_bindDContracts[0]}}</a>
              </li>
            </ul>
          </div>
        </el-col>
      </el-row>
    </div>


    <div class="tcf-table">
      <div class="procurement-contract">
        <div class="procurement-contract-inner">
          <span>采购合同: </span>
          <el-input :readonly="hasBind ? (!editable) : true" v-model="data.documentprocess_fdn_contracts" placeholder="请输入内容"></el-input>
        </div>
      </div>

      <div class="factory-contact-mode">
        <el-row>
          <el-col :span="24">
            <p>工厂联系方式：</p>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="2"><span>工厂名</span></el-col>
          <el-col :span="22" class="factory">
            <!-- <el-input :readonly="hasBind ? (!editable) : true" v-model="data.documentprocess_fdn_fc_factoryName" placeholder="请输入内容"></el-input> -->

         <el-select v-model="currentSel" :disabled="hasBind ? (!editable) : true"  filterable @change="selFactory"  placeholder="请选择工厂/可搜索">
           <el-option
              v-for="item in sellOptions"
             :key="item.value"
             :label="item.label"
             :value="item.value">
            </el-option>
          </el-select>
          </el-col>
        </el-row>

        <!-- <el-row v-for="(item, index) in data.documentprocess_fdn_fc_dff_contacts " :key="index"> -->
        <el-row>
          <el-col :span="2"><span>联系人</span></el-col>
          <el-col :span="3">
            <el-input :readonly="true" v-model="factoryMesg.name" placeholder="请输入内容"></el-input>
          </el-col>
          <el-col :span="1"><span>电话</span></el-col>
          <el-col :span="4">
            <el-input :readonly="true" v-model="factoryMesg.tel" placeholder="请输入内容"></el-input>
          </el-col>
          <el-col :span="1"><span>QQ</span></el-col>
          <el-col :span="3">
            <el-input :readonly="true" v-model="factoryMesg.qq" placeholder="请输入内容"></el-input>
          </el-col>
          <el-col :span="1"><span>邮箱</span></el-col>
          <el-col :span="5">
            <el-input :readonly="true" v-model="factoryMesg.email" placeholder="请输入内容"></el-input>
          </el-col>
          <el-col :span="1"><span>微信</span></el-col>
          <el-col :span="3">
            <el-input :readonly="true" v-model="factoryMesg.wechat" placeholder="请输入内容"></el-input>
          </el-col>
          <!-- <el-col :span="3" class="operation" v-if="hasBind ? editable : false">
            <el-button type="text" @click="addContact('fac', index)">添加</el-button>
            <el-button type="text" @click="delContact('fac', index)" >移除</el-button>
          </el-col>
          <el-col :span="3" class="operation" v-else>
            <span>无权限操作</span>
          </el-col> -->
        </el-row>
      </div>
      <div class="factory-contact-mode">
        <el-row>
          <el-col :span="24">
            <p>物流公司联系方式：</p>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="2"><span>物流公司名</span></el-col>
          <el-col :span="22">
            <el-input :readonly="hasBind ? (!editable) : true" v-model="data.documentprocess_fdn_lcc_logisticName" placeholder="请输入内容"></el-input>
          </el-col>
        </el-row>
        <el-row v-for="(item,index) in data.documentprocess_fdn_lcc_dfl_contacts" :key="index">
          <el-col :span="2"><span>联系人</span></el-col>
          <el-col :span="3">
            <el-input :readonly="hasBind ? (!editable) : true" v-model="item.name" placeholder="请输入内容"></el-input>
          </el-col>
          <el-col :span="1"><span>电话</span></el-col>
          <el-col :span="3">
            <el-input :readonly="hasBind ? (!editable) : true" v-model="item.tel" placeholder="请输入内容"></el-input>
          </el-col>
          <el-col :span="1"><span>QQ</span></el-col>
          <el-col :span="3">
            <el-input :readonly="hasBind ? (!editable) : true" v-model="item.qq" placeholder="请输入内容"></el-input>
          </el-col>
          <el-col :span="1"><span>邮箱</span></el-col>
          <el-col :span="3">
            <el-input :readonly="hasBind ? (!editable) : true" v-model="item.email" placeholder="请输入内容"></el-input>
          </el-col>
          <el-col :span="1"><span>微信</span></el-col>
          <el-col :span="3">
            <el-input :readonly="hasBind ? (!editable) : true" v-model="item.wechat" placeholder="请输入内容"></el-input>
          </el-col>
          <el-col :span="3" class="operation" v-if="hasBind ? editable: false">
            <el-button type="text" @click="addContact('log', index)">添加</el-button>
            <el-button type="text" @click="delContact('log', index)" >移除</el-button>
          </el-col>
          <el-col :span="3" class="operation" v-else>
            <span>无权限操作</span>
          </el-col>
        </el-row>
      </div>

      <el-table :data="tableData" border style="width: 100%" :span-method="arraySpanMethod">

        <el-table-column type="index" label="序号" :index="indexMethod"></el-table-column>
        <el-table-column prop="dd_products" label="产品" width="180">
          <template slot-scope="scope">
                    <el-input :readonly="hasBind ? (!editable) : true" v-model="scope.row.dd_products" placeholder="请输入内容"></el-input>
                </template>
        </el-table-column>
        <el-table-column prop="dd_description" label="规格型号">
          <template slot-scope="scope">
                    <el-input :readonly="hasBind ? (!editable) : true" v-model="scope.row.dd_description" placeholder="请输入内容"></el-input>
                </template>
        </el-table-column>
        <el-table-column prop="dd_quantity" label="数量">
          <template slot-scope="scope">
                    <el-input-number :readonly="hasBind ? (!editable) : true" :controls="false" @change="handleInputChange" v-model="scope.row.dd_quantity" placeholder="请输入内容"></el-input-number>
                </template>
        </el-table-column>
        <el-table-column prop="dd_price" label="单价">
          <template slot-scope="scope">
                    <el-input-number :readonly="hasBind ? (!editable) : true" :controls="false" @change="handleInputChange" v-model="scope.row.dd_price" placeholder="请输入内容"></el-input-number>
                    <!-- <input type="number" :readonly="hasBind ? (!editable) : true"  @input="handleInputChange" v-model="scope.row.dd_price"/> -->
                </template>
        </el-table-column>
        <el-table-column prop="dd_lineAmount" label="金额">
          <template slot-scope="scope">
                    <input type="number" :readonly="true" v-model="scope.row.dd_lineAmount" placeholder="请输入内容"/>
                </template>
        </el-table-column>

        <el-table-column
        v-if="hasBind ? editable: false"
        label="操作"
        width="100">
        <template slot-scope="scope">
          <el-button @click="addNewLine(scope.$index, data.documentprocess_deliDetail)" type="text" size="small">添加</el-button>
          <el-button @click="removeCurrentLine(scope.$index, data.documentprocess_deliDetail)" type="text" size="small">移除</el-button>
        </template>
      </el-table-column>
      </el-table>

      <div class="factory-contact-mode">
        <el-row>
          <el-col :span="24">
            <p>发货情况说明：</p>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="4"><span>发货时间：</span></el-col>
          <el-col :span="20">
            <el-date-picker format="yyyy 年 MM 月 dd 日" value-format="yyyy-MM-dd" :disabled="hasBind ? (!editable) : true"  @change="mustUpdate2"   v-model="documentprocess_fdn_time" type="date" placeholder="选择日期">
            </el-date-picker>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="4"><span>交易方式：</span></el-col>
          <el-col :span="20">
            <el-input :readonly="hasBind ? (!editable) : true"  v-model="data.documentprocess_fdn_tradeTerm" placeholder="请输入内容"></el-input>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="4"><span>产品海关编码：</span></el-col>
          <el-col :span="20">
            <el-input :readonly="hasBind ? (!editable) : true" v-model="data.documentprocess_fdn_hscode" placeholder="请输入内容"></el-input>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="4"><span>其他情况说明：</span></el-col>
          <el-col :span="20">
            <el-input :readonly="hasBind ? (!editable) : true" v-model="data.documentprocess_fdn_other" placeholder="请输入内容"></el-input>
          </el-col>
        </el-row>
      </div>

    </div>



    <div class="upload">
      <p class="upload-hint">票据/附件</p>
      <div>
        <div class="upload-btn">
          <input type="file"  v-show="hasBind ? editable : false"  name="file" multiple @change="selectFiles">
          <el-button  :disabled="hasBind ? (!editable) : true" type="primary">选择附件</el-button>
        </div>

        <ul class="upload-files">
          <li @mouseover="handleOver(item)"   @mouseout="handleOut(item)" v-for="(item,index) in data.attachedFiles" :key="index">
            <span @click="download(item.id, $event)">{{item.name}}</span>
            <span v-if="editable && item.status" class="el-icon-circle-check" style="color:#67c23a;"></span>
            <span v-else-if="editable" class="el-icon-circle-close" @click="changeFiles(index,item)" style="color:red;"></span>
          </li>
        </ul>
      </div>
    </div>

  </div>

  <div class="bind-window">
    <el-dialog title="订单绑定" width="70%" :visible.sync="dialogCtrl.outerVisible">

      <el-form :inline="true">
        <el-form-item label="订单编号">
          <el-input v-model="orderNumber" placeholder="请输入订单编号"></el-input>
        </el-form-item>
        <el-form-item label="外贸合同号">
          <el-input v-model="foreignTradeContractNumber" placeholder="请输入外贸合同号"></el-input>
        </el-form-item>

        <el-form-item label="买家名称">
          <el-input v-model="buyerName" placeholder="请输入买家名称"></el-input>
        </el-form-item>


        <el-form-item>
          <el-date-picker
          v-model="orangeDate"
          type="daterange"
          align="right"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :picker-options="pickerOrange">
        </el-date-picker>
      </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="queryFtc(-1)">查询</el-button>
        </el-form-item>
      </el-form>

      <el-table v-loading="loading" :data="table1Data" style="width: 100%" border stripe>
        <el-table-column prop="table1_orderNumber" label="订单编号" sortable width="240" :sort-method="table1Sort">
          <template slot-scope="scope">
            <span>
              <input type="checkbox" :value="scope.row.table1_id" @click="checkBoxRadio('selForder', $event)" v-model="selectOrder">
              <span>{{scope.row.table1_orderNumber}}</span>
            </span>
          </template>
        </el-table-column>

        <el-table-column prop="table1_ftcNumber" label="外贸合同号" sortable>
        </el-table-column>

        <el-table-column prop="table1_createTime" label="订单生成时间" >
        </el-table-column>

        <el-table-column prop="table1_buyerName" label="买家名称" >
        </el-table-column>



        <el-table-column prop="table1_orderProcess" label="订单流程" >
        </el-table-column>

        <el-table-column prop="table1_orderStatus" label="订单状态" >
        </el-table-column>
      </el-table>


      <div class="pageing">
        <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page.currPage"
        :page-sizes="[20, 30, 50, 100]"
        :page-size="page.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="page.totalSize">
      </el-pagination>

    </div>


      <el-dialog width="50%" title="内贸合同绑定" :visible.sync="dialogCtrl.innerVisible" append-to-body>

        <el-table v-loading="loading" :data="table2Data" style="width: 100%" border>
          <el-table-column prop="table2_dtcNumber" label="内贸合同编号" width="200">
            <template slot-scope="scope">
              <span>
                <input type="checkbox" @click="checkBoxRadio('selDorder', $event)" :value="scope.row.table2_id" v-model="selectOrder2">
                <span>{{scope.row.table2_dtcNumber}}</span>
              </span>
            </template>
          </el-table-column>

          <el-table-column prop="table2_sellerName" label="供方名称">
          </el-table-column>

          <el-table-column prop="table2_contractAmount" label="合同金额">
          </el-table-column>
        </el-table>

        <div slot="footer" class="dialog-footer">
          <el-button type="primary" :disabled="canNotSelect2" @click="bindInnerConfirm">确定</el-button>
          <el-button @click="bindInnerCancel">取 消</el-button>
        </div>
      </el-dialog>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :disabled="canNotSelect" @click="bindOuterSelect">选择内贸合同</el-button>
        <el-button @click="bindOuterCancel">取 消</el-button>
      </div>

    </el-dialog>
  </div>

</div>
</template>

<script>
import {
  uploadFiles,
  queryBindContracts,
  queryBindDtcContracts,
  queryFtcContract,
  queryFtcContractTable,
  getBusinessMesg
} from '@/server/initiatingprocess';

import {filedownload , deleteFile} from '@/server/customermanagement/index.js'
import {setStore, getStore,removeStore} from '@/assets/js/common.js'
import {toFixed} from '@/util/transform.js'


export default {
  created(){
    this.hasBind = this.fromDTab;
    this.documentprocess_fdn_time =  this.data.documentprocess_fdn_time;
    this.currencyValue = this.data.documentprocess_fdn_currencyValue;

    getBusinessMesg({type: 2}).then(response => {
      this.allSellers = response.data.datas; 
      //卖家信息 == 工厂信息
      //设置成下拉列表

      this.allSellers.forEach((e, i, a) => {
        this.sellOptions.push({
          value: e.customerName,
          labe: e.customerName
        });
      });
    })
  },
  updated() {
    if (this.data.createTime && this.first == 0){

      this.currencyValue = this.data.documentprocess_fdn_currencyValue;
      this.documentprocess_fdn_time = this.data.documentprocess_fdn_time;

      let fmsg =  _.cloneDeep(this.data.documentprocess_fdn_fc_dff_contacts[0]);
      
        this.factoryMesg.name =  fmsg.name;
        this.factoryMesg.tel =  fmsg.tel;
        this.factoryMesg.email =  fmsg.email;
        this.factoryMesg.qq =  fmsg.qq;
        this.factoryMesg.wechat  = fmsg.wechat;

        // getBusinessMesg({type: 2}).then(response => {
        //   let curr = response.data.datas.find(item => {
        //     return item.customerContacts == fmsg.name;
        //   });
        //   this.currentSel =  curr.customerName; 
        // });

        this.currentSel = fmsg.factoryName;

        this.first++;
    }
    
    if (this.fromDTab){
        this.hasBind = this.fromDTab;
    }
    this.updateTableData();
  },
  mounted() {
    let that = this;
    let closeDom = document.querySelectorAll('.bind-window i.el-dialog__close.el-icon-close');
    for (let i = 0; i < closeDom.length; i++) {
      closeDom[i].onclick = function() {
        that.bindInnerCancel();
      };
    }
  },
  methods: {

    indexMethod(value) {
      let lines = this.data.documentprocess_deliDetail.length;
      if (lines - 1 === value) {
        return '合计Total';
      }
      return value + 1;
    },
    mustUpdate(){
      this.$forceUpdate();
    },
    mustUpdate2(){
      this.data.documentprocess_fdn_time = this.documentprocess_fdn_time;
      this.$forceUpdate();
    },

    //   合并单元格
    arraySpanMethod(row) {
      let lines = this.data.documentprocess_deliDetail.length;
      if (row.rowIndex === lines - 1) {
        if (row.columnIndex === 0) {
          return [1, 3];
        } else if (row.columnIndex === 1 || row.columnIndex === 2 || row.columnIndex === 6 ) {
          return [0, 0];
        } //else if (row.columnIndex === 3 || row.columnIndex === 5){
        //   return [1, 2];
        // }
      }
    },
    specialInitialProcess() {
      let dom = document.querySelector('.initiatingprocess .routers-ctrl');
      if (dom) {
        dom.style.zIndex = '0';
      }
    },
    bindOrder(){
      this.dialogCtrl.outerVisible = true;
      this.bindFContracts = [];
      this.bindDContracts = [];

      this.canNotSelect = true;
      this.canNotSelect2 = true;

      this.orderNumber = '';
      this.foreignTradeContractNumber = '';
      this.buyerName = '';

      this.queryFtc(1, 30);
    },

    handleSizeChange(size){
      this.page.pageSize = size;
      //需要重新查询
      this.queryFtc(1, this.page.pageSize);
    },
    handleCurrentChange(currPage){
      this.page.currPage = currPage;
      //需要重新查询
      this.queryFtc(this.page.currPage, this.page.pageSize);
    },
    queryFtc(currPage, pageSize) {

      let startTime, endTime;
      //通过查询来获得外贸合同订单，并修改table1的数据来进行显示
      if (currPage ==  -1){
        currPage = 1;
        this.page.currPage = 1;
        pageSize = this.page.pageSize;
      }

      this.table1Data = [];
      this.table2Data = [];
      this.selectOrder = [];
      this.loading = true;


      if (this.orangeDate) {
        startTime = new Date('' + this.orangeDate[0]).getTime();
        endTime = new Date('' + this.orangeDate[1]).getTime();

        queryBindContracts({
          flowId: 1,
          orderCode: this.orderNumber,
          ftcCode: this.foreignTradeContractNumber,
          buyerName: this.buyerName,
          currPage: currPage - 1,
          pageSize: pageSize,
          gt_createTime: startTime,
          lt_createTime: endTime
        }).then((response)=>{

  

          this.page.totalSize = response.data.totalSize;
          this.queryOrderData = response.data.datas;

          this.loading = false;

          let table1Data = this.table1Data;
          for (let i = 0; i < this.queryOrderData.length; i++) {

            if (!table1Data[i]) {
              table1Data[i] = {};
            }
            table1Data[i].table1_orderNumber = this.queryOrderData[i].orderCode;
            table1Data[i].table1_ftcNumber = this.queryOrderData[i].ftcCode;
            table1Data[i].table1_buyerName = this.queryOrderData[i].buyerName;
            table1Data[i].table1_id = this.queryOrderData[i].id;







            let date = new Date(this.queryOrderData[i].createTime);
            let m = date.getMonth() + 1;
            m = m < 10 ? '0' + m  : m;
            let d = date.getDate();
            d = d < 10 ? '0' + d  : d;

            table1Data[i].table1_createTime = date.getFullYear() + '-' + m + '-' + d;

            switch(this.queryOrderData[i].formInstStatus){
              case 0:
              case 1:
              table1Data[i].table1_orderStatus = '流转中';
              break;
              case 2:
              table1Data[i].table1_orderStatus = '完结';
              break;
            }

            table1Data[i].table1_orderProcess = this.queryOrderData[i].flowName;
          }

    


          this.$forceUpdate();
        });
      } else {
        queryBindContracts({
          flowId: 1,
          orderCode: this.orderNumber,
          ftcCode: this.foreignTradeContractNumber,
          buyerName: this.buyerName,
          currPage: currPage - 1,
          pageSize: pageSize
        }).then((response)=>{

          

          this.page.totalSize = response.data.totalSize;
          this.queryOrderData = response.data.datas;

          this.loading = false;

          let table1Data = this.table1Data;
          for (let i = 0; i < this.queryOrderData.length; i++) {

            if (!table1Data[i]) {
              table1Data[i] = {};
            }
            table1Data[i].table1_orderNumber = this.queryOrderData[i].orderCode;
            table1Data[i].table1_ftcNumber = this.queryOrderData[i].ftcCode;
            table1Data[i].table1_buyerName = this.queryOrderData[i].buyerName;
            table1Data[i].table1_id = this.queryOrderData[i].id;


            let date = new Date(this.queryOrderData[i].createTime);
            let m = date.getMonth() + 1;
            m = m < 10 ? '0' + m  : m;
            let d = date.getDate();
            d = d < 10 ? '0' + d  : d;

            table1Data[i].table1_createTime = date.getFullYear() + '-' + m + '-' + d;

            switch(this.queryOrderData[i].formInstStatus){
              case 0:
              case 1:
              table1Data[i].table1_orderStatus = '流转中';
              break;
              case 2:
              table1Data[i].table1_orderStatus = '完结';
              break;
            }

            table1Data[i].table1_orderProcess = this.queryOrderData[i].flowName;
          }

          this.$forceUpdate();
        });
      }


    },
    table1Sort(a, b) {
      let a1 = a.toString().slice(a.length - 5);
      let b1 = b.toString().slice(b.length - 5);
      return parseInt(b) - parseInt(b);
    },
    checkBoxRadio(type, event) {
      let value = event.target.value;

      if (type === 'selForder') {

        if (value === this.selectOrder[0]) {
          this.canNotSelect = true;
        } else {
          this.canNotSelect = false;
        }

        this.selectOrder = [value];

        this.showftc = this.queryOrderData.find((e) => {
          return e.id == this.selectOrder[0]
        });

        this.bindFContracts[0] = this.showftc.ftcCode;

      } else if (type === 'selDorder'){
        if (value === this.selectOrder2[0]) {
          this.canNotSelect2 = true;
        } else {
          this.canNotSelect2 = false;
        }

        this.selectOrder2 = [value];

        let currDtc = this.queryOrderData2.find((e) => {
          return e.id == this.selectOrder2[0]
        });

        this.bindDContracts[0] = currDtc.bd_no;
      }
    },
    bindOuterSelect() {
      let that = this;
      this.dialogCtrl.innerVisible = true;

      let closeDom = document.querySelectorAll('i.el-dialog__close.el-icon-close');
      for (let i = 0; i < closeDom.length; i++) {
        closeDom[i].onclick = function() {
          that.bindInnerCancel();
        };
      }

      /*
      需要根据当前选中的订单值即 checkedFOrder,来修改 table2Data，用于显示该订单下的内贸订单
      */

      //勾选的外贸
      // this.showftc = this.queryOrderData.find((e)=>{
      //   return e.ftcCode == this.bindFContracts[0]
      // });

      this.data.buyerName = this.showftc.buyerName;
      this.data.orderCode = this.showftc.orderCode;

      //绑定的外贸订单的id
      this.data.bindingFormInstId = this.showftc.id;

      this.loading = true;

      queryBindDtcContracts({
        formInstId: this.showftc.id
      }).then((response)=>{
        this.queryOrderData2 = response.data.datas;
        this.loading = false;

        let table2Data =  this.table2Data;

        for (let i = 0; i < this.queryOrderData2.length; i++) {

          if (!table2Data[i]) {
            table2Data[i] = {};
          }
          table2Data[i].table2_dtcNumber = this.queryOrderData2[i].bd_no;
          table2Data[i].table2_sellerName = this.queryOrderData2[i].bd_seller;
          table2Data[i].table2_contractAmount = this.queryOrderData2[i].bd_table1_totalAmount;
          table2Data[i].table2_id = this.queryOrderData2[i].id;
        }
        this.$forceUpdate();
      });

    },
    bindOuterCancel() {
      this.bindInnerCancel();
    },
    bindInnerConfirm() {
      this.dialogCtrl.outerVisible = false;
      this.dialogCtrl.innerVisible = false;

      if (this.bindDContracts.length === 0) {
        this.bindInnerCancel();
        return;
      }

      this.hasBind = true;
      this.data.documentprocess_fdn_bindFContracts = _.cloneDeep(this.bindFContracts);
      this.data.documentprocess_fdn_bindDContracts = _.cloneDeep(this.bindDContracts);

       //勾选的内贸
       // this.showdtcs = this.queryOrderData2.filter((e)=>{
       //    return this.data.documentprocess_fdn_bindDContracts.indexOf(e.bd_no) != -1;
       // });

       this.showdtcs[0] = this.queryOrderData2.find((e)=>{
          return this.data.documentprocess_fdn_bindDContracts[0] == e.bd_no;
       });

       this.data.documentprocess_fdn_contracts = this.showdtcs[0].bd_no;

       //保存一下绑定的内贸合同的formInstId
      //  setStore("formInstId", this.showdtcs[0].formInstId);

       queryFtcContract({
         formInstId: this.showftc.id,
       }).then((response) => {
         let ftc = response.data.datas[0];

         queryFtcContractTable({
           formInstId: this.showftc.id,
           ftcId: ''
         }).then((response) => {

           //得到绑定的外贸合同
           let ftcData = _.extend({}, ftc, {bf_table1:response.data.datas});

           this.bus.$emit('bind-new-ftc', ftcData);

           this.table1Data = [];
           this.table2Data = [];
           this.page.pageSize = 30;
           this.$forceUpdate();
         });

       });

    },
    bindInnerCancel() {
      this.dialogCtrl.outerVisible = false;
      this.dialogCtrl.innerVisible = false;
      this.bindFContracts = [];
      this.bindDContracts = [];

      this.canNotSelect = true;
      this.canNotSelect2 = true;

      this.selectOrder = [];

      this.page.pageSize = 30;
      this.table1Data = [];
      this.table2Data = [];
      this.$forceUpdate();
    },
    selectFiles(event) {
      //票据附件
      let _this = this;


      //直接上传，并且获得后端返回的文件的url,将url保存到 this.data.attachedFiles中
      uploadFiles(event.target.files).then((resArr)=>{
        resArr.forEach(function(res,i){
          _this.data.attachedFiles.push({name: event.target.files[i].name, status: 1, id: res.data.datas[0].id});
        });

        _this.$forceUpdate();
      });
    },
    changeFiles(index,item) {
      deleteFile({'id':item.id}).then((res) => {
        if(res.code != 1 ){
          this.$message.error('删除失败，请检查网络后重试');
        } else {
          this.data.attachedFiles.splice(index, 1);
        }
      });
    },
    handleOver(item){
      item.status = 0;
      this.$forceUpdate();
    },
    handleOut(item){
      item.status = 1;
      this.$forceUpdate();
    },
    download(id, event){
      window.open('http://47.104.93.41/api/common/download?id='+id);
    },

    addNewLine(currentIndex, table){
      let newLine = _.cloneDeep(table[0]);

      _.unset(newLine, 'id');
      _.unset(newLine, 'createTime');
      _.unset(newLine, 'dpfdId');
      _.unset(newLine, 'formInstId');
      _.unset(newLine, 'modifyTime');

      for (let prop in newLine) {
        newLine[prop] = '';
      }

      table.splice(currentIndex + 1, 0, newLine);
    },
    removeCurrentLine(currentIndex, table){
      if (table.length > 2){
        table.splice(currentIndex, 1);
      }
    },

    addContact(type, index){
      if (type == 'fac'){
        let newLine = _.cloneDeep(this.data.documentprocess_fdn_fc_dff_contacts[0]);
        for (var prop in newLine) {
          newLine[prop] = '';
        }
        this.data.documentprocess_fdn_fc_dff_contacts.splice(index + 1, 0, newLine);
      } else if (type == 'log'){
        let newLine = _.cloneDeep(this.data.documentprocess_fdn_lcc_dfl_contacts[0]);
        for (var prop in newLine) {
          newLine[prop] = '';
        }
        this.data.documentprocess_fdn_lcc_dfl_contacts.splice(index + 1, 0, newLine);
      }

      this.$forceUpdate();
    },
    delContact(type, index){
      if (type == 'fac'){
        if (this.data.documentprocess_fdn_fc_dff_contacts.length > 1){
          this.data.documentprocess_fdn_fc_dff_contacts.splice(index, 1);
          this.$forceUpdate();
        }
      } else if (type == 'log'){
        if (this.data.documentprocess_fdn_lcc_dfl_contacts.length > 1){
          this.data.documentprocess_fdn_lcc_dfl_contacts.splice(index, 1);
          this.$forceUpdate();
        }
      }
    },
    exportMethod() {},

    handleInputChange() {
      this.updateTableData();
      this.$forceUpdate();
      this.$forceUpdate();
    },
    updateTableData() {
      let amounts = 0,quantitys = 0,
      current = this.data.documentprocess_deliDetail;
      let lines = current.length, temp = 0;

      for (let i = 0; i <  lines - 1; i++) {
        current[i].dd_price  = toFixed(current[i].dd_price, 2);
        current[i].dd_quantity = parseInt(current[i].dd_quantity);

        temp = current[i].dd_price * current[i].dd_quantity;
        current[i].dd_lineAmount =  toFixed(temp, 2);
        amounts += parseFloat(temp);
        quantitys += parseInt(current[i].dd_quantity);
      }

      current[lines - 1].dd_lineAmount = toFixed(amounts, 2);
      current[lines - 1].dd_quantity = quantitys;
    },
    selFactory(value){
      let currentFactory = this.allSellers.find(e => {
        return e.customerName == this.currentSel;
      });

      this.data.documentprocess_fdn_fc_dff_contacts = [{
        name: currentFactory.customerContacts,
        tel: currentFactory.customerPhone,
        email: currentFactory.customerEmail,
        qq: currentFactory.customerQQ || '',
        wechat: currentFactory.customerWechat,
        factoryName: currentFactory.customerName
      }];

      this.factoryMesg = {        
        name: currentFactory.customerContacts,
        tel: currentFactory.customerPhone,
        email: currentFactory.customerEmail,
        qq: currentFactory.customerQQ || '',
        wechat: currentFactory.customerWechat
      };
   },

       /**选择币种 */
    currencySel(name){
        return (h, {column, $index}) => {
        let self = this;
        return  h("div", {
          attrs: {
            class: "select-currency"
          }
        }, [
          h("span", name),
          h("select", {domProps: {
            value: self.currencyValue
          },
          on: {
            change: function(event){
              self.currencyValue = event.target.value;
              self.data.documentprocess_fdn_currencyValue = event.target.value;
            }
          }
          },[
            h("option", "人民币"),
            h("option", "美元"),
            h("option", "加元"),
            h("option", "欧元"),
          ])
        ]);
      }
    }
  },
  computed: {
    //   表格计算总金额
    tableData() {
      let amounts = 0, quantitys = 0,
        current = this.data.documentprocess_deliDetail;
      let lines = current.length, temp = 0;

      for (let i = 0; i < lines - 1; i++) {
        temp = current[i].dd_price * current[i].dd_quantity;
        current[i].dd_lineAmount =  toFixed(temp, 2);
        amounts += parseFloat(temp);
        quantitys += parseInt(current[i].dd_quantity);
      }


      amounts = amounts.toString().replace(/(\d.\d\d)(\d+)/g, function(match, p1, p2){
        return p1;
      });
      current[lines - 1].dd_lineAmount = toFixed(amounts, 2);
      current[lines - 1].dd_quantity = quantitys;

      return current;
    }
  },
  data() {
    return {
      dialogCtrl: {
        outerVisible: false,
        innerVisible: false,
      },
      page: {
        currPage: 1,
        pageSize: 30,
        totalSize: 0
      },
      documentprocess_fdn_time: '',
      loading: false,
      bindFContracts: [],
      bindDContracts: [],
      selectOrder:[],
      selectOrder2:[],
      dialogVisible: false, //默认点击发送的弹窗不显示
      canNotSelect: true,
      canNotSelect2: true,
      hasBind: false,
      orderNumber: '',
      foreignTradeContractNumber: '',
      buyerName: '',
      queryOrderData: [],
      queryOrderData2: [],
      table1Data: [],
      table2Data: [],
      showftc: null,
      showdtcs: [],
      orangeDate: '',
      pickerOrange:{
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }]
        },
      allSellers: [],
      sellOptions: [],
      currentSel: "",
      factoryMesg: {
        name: "",
        tel: "",
        email: "",
        qq: "",
        wechat: ""
      },
      currencyValue: '人民币',
      first: 0
    }
  },
  props: {
    data: {
      type: Object,
      required: true
    },
    editable: {
      type: Boolean,
      required: true
    },
    bus: {
      type: Object,
      required: true
    },
    fromDTab: {
      type: Boolean,
      required: true
    }
  },
  components: {}
}
</script>

<style  lang="scss">
body {
    .dialog-footer {
        text-align: center;
        button {
            margin-right: 50px;
        }
    }
}

.noticeofdelivery {
    padding: 20px;
    border: 1px solid #999;
    > h2 {
        text-align: center;
    }

  .select-currency {
      select {
        margin-left: 12px;
        height: 30px;
        width: 60px;
      }
    }

    .factory .el-select {
      width: 100%;
    }

    font-size: 15px;

    a {
        color: #409EFF;
      }

      .el-col-offset-4 {
        margin-left: 16.66667% !important;
      }


      .el-input-number__decrease,
      .el-input-number__increase {
        width: 20px;

        border: none !important;
        background: transparent;
      }

      .el-input-number {
          width: 100%;
          min-width: 100px;
      }


      .tcf-table {
        .el-col {
          border: none !important;
          padding-right: 5px;
          border-bottom: 1px solid #999 !important;
          border-right: 1px solid #999 !important;
          margin-left: 0 !important;
        }
      }

    .el-table {
        margin-bottom: 20px;

        td {
            border: 1px solid #e6ebf5;
        }
    }

    .head {
      position: relative;

      >h2 {
        text-align: center;
      }


        .select-orders {

            padding: 30px 20px;

            li {
                padding: 5px 0;
            }

            .select-orders-line {
              height: 40px;
              line-height: 40px;
            }

            .el-col {
                border: none !important;
            }
        }

        .el-input__inner {
            border: none;
            outline: none;
            background: transparent;
        }

        .procurement-contract {
            width: 100%;
            height: 40px;
            margin-bottom: 20px;
            text-align: right;
            .procurement-contract-inner {
                width: 50%;
                float: right;
                span {
                    display: inline-block;
                    width: 30%;
                }
                .el-input {
                    width: 65%;
                }
            }

        }
        .factory-contact-mode {
            width: 100%;
            border-top: 1px solid #999;
            border-left: 1px solid #999;
            margin-bottom: 20px;

            font-size: 12px;

            .el-input__inner {
                border: none;
                outline: none;
            }

            .el-row {

              transition: all 0.2s linear;
              &:hover {
                background-color: #c5e8ff !important;
              }
            }

            .operation {
              text-align: center;
              color: #409EFF;
              >button {
                padding: 0 2px;
                font-size: 12px;
                cursor: pointer;
              }
            }
        }
        .btns {
            position: absolute;
            top: -6px;
            padding: 0 20px;
            text-align: center;

            .bind {
                float: left;
            }
            .export {
                float: right;
            }
        }

        .tcf-table {
            margin-top: 20px;
            padding: 20px;
            box-sizing: border-box;
            content: "";
            width: 100%;
            clear: both;

             input {
              border: none;
              outline: none;
              background-color: transparent;
              height: 100%;
            }

            h2 {
                text-align: center;
                padding: 10px 0;
            }

            .tcf-table-title {
                text-align: center;
            }

            .el-col {
                height: 50px;
                line-height: 50px;
                border: 1px solid #999;
                margin-left: -1px;
                margin-top: -1px;
                padding-left: 5px;
            }

            .no-border {
                //   border: none !important;
            }

            .special-row {
                .el-col {
                    height: 25px;
                    line-height: 25px;
                }
            }
        }

        .upload {
            > div {
                border: 1px solid #999;
                padding: 20px 0 40px 20px;
            }

            .upload-btn {
                position: relative;
                > input {
                    opacity: 0;
                    width: 100px;
                    height: 40px;
                    position: absolute;
                    top: 0;
                    left: 0;
                }
            }

            .upload-files {

                > li {
                    width: 300px;
                    padding: 10px 0;
                    transition: all 0.5s linear;

                    &:hover {

                      >span {
                        color: #409EFF;
                      }
                    }
                  }

                font-size: 16px;
                span {
                    padding: 0 10px;
                    cursor: pointer;
                    display: inline;
                }
                span.el-icon-close:hover {
                    cursor: pointer;
                }
            }
            .upload-hint {
                font-size: 20px;
                margin-bottom: 10px;
            }
        }
    }

    .bind-window {
        .el-form--inline .el-form-item {
            margin-right: 15px;
        }

        td {
            border: 1px solid #e6ebf5;
        }

        td:not(.el-table_1_column_1) {
            width: 120px;
            min-width: 120px;
        }

        .dialog-footer {
            text-align: center;
            button {
                margin-right: 80px;
            }
        }

        a {
            color: #409EFF;
        }

    }
}
</style>
